import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    activeTab: "all",
    todos: JSON.parse(localStorage.getItem("todos-vuex")) || [],
  },
  getters: {
    activeTab:function (state) {
        return state.activeTab;
    },
    remaining: function (state) {
      let remainingTodos = state.todos.filter((v) => {
        return !v.status;
      });
      return remainingTodos.length;
    },
    filterTodos: function (state) {
      if (state.activeTab === "all") {
        return state.todos;
      } else if (state.activeTab === "active") {
        return state.todos.filter((v) => {
          return !v.status;
        });
      } else {
        return state.todos.filter((v) => {
          return v.status;
        });
      }
    },
    allChecked: function (state) {
      let checked = true;
      state.todos.map((v) => {
        if (!v.status)  checked = false;
      });
      return checked;
    },
  },
  mutations: {
    handleItemClick: function (state,{payload}) {
        state.activeTab = payload.activeTab;
    },
    addTodo:function (state,{payload}) {
        state.todos.push(payload);
    },
    handleAllCheck: function (state) {
        if (!this.getters.allChecked) {
            let newTodos = JSON.parse(JSON.stringify(state.todos));
            newTodos.map((v) => {
                v.status = true;
            });
            return state.todos = newTodos;
        } else {
            let newTodos = JSON.parse(JSON.stringify(state.todos));
            newTodos.map((v) => {
                v.status = false;
            });
            return state.todos = newTodos;
        }
    },
    clearCompleted: function (state) {
      let activeTodos = state.todos.filter((v) => {
        return !v.status;
      });
      state.todos = activeTodos;
    },
    deleteTodo: function (state,{payload}) {
        state.todos.splice(payload.index, 1);
    },
  },
  actions: {},
  modules: {},
});
